package com.muyaxuan.mail.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.muyaxuan.mail.common.FileUpload;
import com.muyaxuan.mail.common.PageModel;
import com.muyaxuan.mail.common.WebConstant;
import com.muyaxuan.mail.dao.GoodsDao;
import com.muyaxuan.mail.dao.GoodsTypeDao;
import com.muyaxuan.mail.dto.Goods;

@Controller
@RequestMapping("/admin/goods")
public class GoodsController {
	PageModel pageModel = new PageModel();
	GoodsDao goodsDao = null;
	GoodsTypeDao goodsTypeDao = null;
	/**
	 * 删除商品
	 * @return
	 */
	@RequestMapping("/deleteGoods")
	public String deleteGoods(int id){
		
		goodsDao.deleteGoods(id);
		
		return "redirect:/admin/goods/showGoodsList";
	}
	/**
	 * 分页查询商品
	 * @param title
	 * @param pageIndex
	 * @param data
	 * @return
	 */
	
	@RequestMapping("/showGoodsList")
	public String showGoodsList(String title,@RequestParam(name="pageIndex",defaultValue="0")int pageIndex,Model data){
		
		goodsDao = new GoodsDao(); 
		
		pageModel.setPageIndex(pageIndex);
		
		Map<String,Object> params = new HashMap<>();
		
		int recordCount = goodsDao.count(title);
		
		pageModel.setRecordCount(recordCount);
		
		params.put("title", title);
		params.put("pageModel", pageModel);
		
		List<Goods> goodsList = goodsDao.getGoodsByPage(params);
		
		data.addAttribute("goodsList", goodsList);
		data.addAttribute("pageModel", pageModel);
		data.addAttribute("title", title);
		
		return "goods/goodsList";
	}
	/**
	 * 去添加商品页面
	 * @return
	 */
	@RequestMapping("/showAddGoods")
	public String showAddGoods(Model data){

		return "goods/addGoods";
	}
	/**
	 * 添加商品
	 * @param goods
	 * @return
	 */
	@RequestMapping("/addGoods")
	public String register(@RequestParam("pic")MultipartFile file,Goods goods,HttpSession session){
		try {
			String fileName = FileUpload.imgsUpload(file, session, WebConstant.GOODS_IMG_PATH);
			goods.setImage(fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		goods.setCreateDate(new Date());
		
		goodsDao.addGoods(goods);

		return "redirect:/admin/goods/showGoodsList";
	}
	/**
	 * 上传图片 ajax
	 * @param file
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/imgUpload")
	public String fileUpload(@RequestParam("pic")MultipartFile file,HttpSession session) throws Exception{
		
		String fileName = FileUpload.imgsUpload(file, session, WebConstant.GOODS_DESCIMG_PATH);
		return fileName;
	}
	
	
	
	
	
	
}
